var ctx;
/*var pwdReg = /^(?![^a-zA-Z]+$)(?!\D+$).{8,30}$/; //至少包含字母数字的验证
*/
var pwdReg = /^\S{6,15}$/;
function setCtx(ctx) {
	this.ctx = ctx;
}
var cellInfoId = "";
var cellRegionId = "";
var cellBuildingId = "";
var cellUnitId = "";
var ownerHouseId = "";
$(function(){

	$("#province").change(function () {
		province = $('#province').val();
		if (province != '') {
			$.ajax({
		        type : "GET",
		        url : ctx + "/district/getDistrictInfoByParentId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	parentId : province
		        },
		        success : function(data) {
		        	if (data.success) {
		                var result = "<option value='" + "'>--城市--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.regionName + "'" + " value='" + item.id + "'>" + item.regionName + "</option>";
		                });
		                $("#city").html('');
		                $("#city").append(result);
		                $("#city").change();
		            }
		        }
			});
		} else {
			var result = "<option value='" + "'>--城市--</option>";
			$("#city").html('');
            $("#city").append(result);
            $("#city").change();
		}
    });
	
    $("#city").change(function () {
    	city = $('#city').val();
    	if (city != ''){
    		$.ajax({
		        type : "GET",
		        url : ctx + "/district/getDistrictInfoByParentId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	parentId : city
		        },
		        success : function(data) {
		        	if (data.success) {
		        		var result = "<option value='" + "'>--区--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.regionName + "'" + " value='" + item.id + "'>" + item.regionName + "</option>";
		                });
		                $("#district").html('');
		                $("#district").append(result);
		                $("#district").change();
		            }
		        }
			});
    	} else {
    		var result = "<option value='" + "'>--区--</option>";
			$("#district").html('');
            $("#district").append(result);
            $("#district").change();
    	}
    });
    
    
    $("#district").change(function () {
    	area = $('#district').val();
    	if (area != ''){
    		$.ajax({
		        type : "GET",
		        url : ctx + "/ownerHouse/getCellListByAreaId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	areaId : area
		        },
		        success : function(data) {
		        	if (data.success) {
		        		var result = "<option value='" + "'>--小区--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.cellName + "'" + " value='" + item.id + "'>" + item.cellName + "</option>";
		                });
		                $("#cellInfoId").html('');
		                $("#cellInfoId").append(result);
		                $("#cellInfoId").change();
		            }
		        }
			});
    	} else {
    		var result = "<option value='" + "'>--小区--</option>";
			$("#cellInfoId").html('');
            $("#cellInfoId").append(result);
            $("#cellInfoId").change();
    	}
    });
    
    $("#cellInfoId").change(function () {
		cellInfoId = $('#cellInfoId').val();
		if (cellInfoId != '') {
			$.ajax({
		        type : "GET",
		        url : ctx + "/ownerHouse/getCellRegionByCellId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	cellId : cellInfoId
		        },
		        success : function(data) {
		        	if (data.success) {
		                var result = "<option value='" + "'>--区域--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.name + "'" + " value='" + item.id + "'>" + item.name + "</option>";
		                });
		                $("#cellRegionId").html('');
		                $("#cellRegionId").append(result);
		                $("#cellRegionId").change();
		            }
		        }
			});
		} else {
			var result = "<option value='" + "'>--区域--</option>";
			$("#cellRegionId").html('');
            $("#cellRegionId").append(result);
            $("#cellRegionId").change();
		}
    });
	
    $("#cellRegionId").change(function () {
    	cellRegionId = $('#cellRegionId').val();
    	if (cellRegionId != ''){
    		$.ajax({
		        type : "GET",
		        url : ctx + "/ownerHouse/getCellBuildingByRegionId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	regionId : cellRegionId
		        },
		        success : function(data) {
		        	if (data.success) {
		        		var result = "<option value='" + "'>--楼栋--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.buildingName + "'" + " value='" + item.id + "'>" + item.buildingName + "</option>";
		                });
		                $("#cellBuildingId").html('');
		                $("#cellBuildingId").append(result);
		                $("#cellBuildingId").change();
		            }
		        }
			});
    	} else {
    		var result = "<option value='" + "'>--楼栋--</option>";
			$("#cellBuildingId").html('');
            $("#cellBuildingId").append(result);
            $("#cellBuildingId").change();
    	}
    });
    
    $("#cellBuildingId").change(function () {
    	cellBuildingId = $('#cellBuildingId').val();
    	if (cellBuildingId != ''){
    		$.ajax({
		        type : "GET",
		        url : ctx + "/ownerHouse/getCellUnitByBuildingId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	buildingId : cellBuildingId
		        },
		        success : function(data) {
		        	if (data.success) {
		        		var result = "<option value='" + "'>--单元--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.name + "'" + " value='" + item.id + "'>" + item.name + "</option>";
		                });
		                $("#cellUnitId").html('');
		                $("#cellUnitId").append(result);
		                $("#cellUnitId").change();
		            }
		        }
			});
    	} else {
    		var result = "<option value='" + "'>--单元--</option>";
			$("#cellUnitId").html('');
            $("#cellUnitId").append(result);
            $("#cellUnitId").change();
    	}
    });
    
    $("#cellUnitId").change(function () {
    	cellUnitId = $('#cellUnitId').val();
    	
    	if (cellUnitId != ''){
    		$.ajax({
		        type : "GET",
		        url : ctx + "/ownerHouse/getCellHouseByUnitId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	unitId : cellUnitId
		        },
		        success : function(data) {
		        	if (data.success) {
		        		var result = "<option value='" + "'>--门牌号--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.name + "'" + " value='" + item.id + "'>" + item.name + "</option>";
		                });
		                $("#cellHouseId").html('');
		                $("#cellHouseId").append(result);
		                $("#cellHouseId").change();
		            }
		        }
			});
    	} else {
    		var result = "<option value='" + "'>--门牌号--</option>";
			$("#cellHouseId").html('');
            $("#cellHouseId").append(result);
            $("#cellHouseId").change();
    	}
    });
    
    
    $('#cellHouseId').change(function() {
    	if ($('#cellHouseId').val() != 0) {
    		ownerHouseId = $('#cellHouseId').val();
    	}
    });


});
function checkRequiredInput() {
	if(!(checkPhone() && checkCode() && checkNewPwd() && checkNewPwd1())){
		return false;
	}
	
	if(!checkInput('nickName','请输入呢称')){
        $('#nickName').focus();
        return false;
    }
    if(!checkInput('realName','请输入真实姓名')){
        $('#realName').focus();
        return false;
    }
    
    return true;
}
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
function cancel(){
	parent.layer.close(index);
}
function toNext() {
	if(!checkRequiredInput()){
		return;
	}
	// 验证手机号唯一
	$.ajax({
		type : "POST",
		url : ctx + "/checkPhone",
		data : {
			phone : $("#phoneBind").val()
		},
		cache : false,
		async : false,
		dataType : 'json',
		success : function(result) {
			if (result.success) {
				$('#personal_info').hide();
				$('#house_info').show();
				$(".title-right").addClass('select');
				$(".title-left").removeClass('select');
			} else {
				layer.tips(result.msg, '#phoneBind', {
					tips : 3,
					time : 1000
				});
				return false;
			}
		}
	});
	
}

function toPrevious() {
	$('#personal_info').show();
	$('#house_info').hide();
	$(".title-left").addClass('select');
	$(".title-right").removeClass('select');
}

function submit() {
	$('#house_info select').each(function () {
	    if(!checkInput($(this).attr('id'),$(this).attr('title'))){
	        $('#' + $(this).attr('id')).focus();
	        flag = false;
	        return;
	    }
	});
	
	/*if(!checkInput('houseName','请输入门牌号')){
        $('#houseName').focus();
        return false;
    }*/
	
	var info = {};
	if(null != $('#userId').val() && undefined != $('#userId').val()) {
	    info.userId = $('#userId').val();
	} else {
	    info.phone = $('#phoneBind').val();
	    info.nickName = $('#nickName').val();
	    info.realName = $('#realName').val();
	    info.password = encrypt($('#newPwd').val(), $('#nickName').val());
	}
    info.province = $('#province').val();
    info.city = $('#city').val();
    info.district = $('#district').val();
    info.cellInfoId = $('#cellInfoId').val();
    info.cellRegionId = $('#cellRegionId').val();
    info.cellBuildingId = $('#cellBuildingId').val();
    info.cellUnitId = $('#cellUnitId').val();
    info.houseId = $('#cellHouseId').val();
    
    var index1 = layer.load(1);
	$.post(ctx + "/saveRegister", info, function(data) {
		data = JSON.parse(data);
		if (data.success) {
			layer.msg("操作成功", {
				icon : 1,
				time : 1000
			// 2秒关闭（如果不配置，默认是3秒）
			}, function() {
				layer.close(index1);
				parent.layer.close(index); // 根据窗口索引关闭窗口
			});
		} else {
			layer.msg(data.msg, {
				icon : 2,
				time : 1000
			// 2秒关闭（如果不配置，默认是3秒）
			}, function() {
				layer.close(index1);
				parent.layer.close(index); // 根据窗口索引关闭窗口
			});
		}
	});
	
}
//验证手机号
var phoneReg = /^(13[0-9]|15[0-9]|18[0-9]|14[578])[0-9]{8}$/;
function checkPhone() {
	var phoneBind = $("#phoneBind").val();
	//解决ie9以下placeholder与value重复的问题
	if (phoneBind == $("#phoneBind").attr("placeholder")) {
		phoneBind = "";
	}

	if (phoneBind == null || phoneBind == "") {
		layer.tips('手机号不能为空！', '#phoneBind', {
			tips : 3,
			time : 1000
		});
		return false;
	} else if (!phoneReg.test(phoneBind)) {
		layer.tips('电话号码格式错误，请填写正确格式的电话号码!', '#phoneBind', {
			tips : 3,
			time : 2000
		});
		return false;
	} else {
		return true;
	}
};

var sixCode;
var phoneCode;
var timer;
//每隔60s发送一次验证码
$("#sendcode").on("click", function() {
	var checkRe = checkPhone();
	if(!checkRe){
		return;
	}
	//resendTime();
	$.ajax({
		type : "POST",
		url : ctx + "/sendRegisterCode",
		data : {
			phone : $("#phoneBind").val()
		},
		cache : false,
		async : false,
		dataType : 'json',
		success : function(result) {
			console.info(result);
			if (result.success) {
				layer.msg("验证码发送成功", {
					icon : 1,
					time : 2000
				//2秒关闭（如果不配置，默认是3秒）
				});
				$("#sixCode").val(result.obj);
				sixCode = $("#sixCode").val();
			} else {
				layer.msg("验证码发送失败", {
					icon : 2
				});
			}
		}
	});
})

function resendTime() {
	var phone = $("#phone").val();

	if (phone != "" && timer == null) {
		curTime = $("#resendTime").val();
		$("#sendcode").attr("disabled", true);
		$("#sendcode").css("background", "grey");
		$("#warning").text(curTime + "秒后可重发");
		timer = setInterval(handleTimer, 1000);
	}
}
function handleTimer() {
	if (curTime == 0) {
		clearInterval(timer);
		timer = null;
		$("#sendcode").removeAttr("disabled");
		$("#sendcode").css("background", "#ffaa00");
		$("#warning").text("重发验证码");
	} else {

		curTime--;
		$("#warning").text(curTime + "秒后可重发");

	}
}

//验证验证码
function checkCode() {
	var code = $("#phoneCode").val();
	//解决ie9以下placeholder与value重复的问题
	if (code == $("#phoneCode").attr("placeholder")) {
		code = "";
	}
	if (code == null || code == "") {
		layer.tips('请输入验证码！', '#phoneCode', {
			tips : 3,
			time : 1000
		});
		return false;
	} else if (code != sixCode) {
		layer.tips('验证码输入错误，请重新输入！', '#phoneCode', {
			tips : 3,
			time : 1000
		});
		return false;
	} else {
		return true;
	}
}

//验证新密码
function checkNewPwd() {
	var newPwd = $("#newPwd").val();
	//解决ie9以下placeholder与value重复的问题
	if (newPwd == $("#newPwd").attr("placeholder")) {
		newPwd = "";
	}
	if (newPwd == null || newPwd == "") {
		layer.tips('请输入密码！', '#newPwd', {
			tips : 3,
			time : 1000
		});
		return false;
	} else {
		if (!pwdReg.test(newPwd)) {
			layer.tips('密码格式为6-15位非空字符!', '#newPwd', {
				tips : 3,
				time : 2000
			});
			return false;
		} else {
			return true;
		}
	}
}

//再次验证新密码
function checkNewPwd1() {
	var newPwd1 = $("#newPwd1").val();
	var newPwd = $("#newPwd").val();
	//解决ie9以下placeholder与value重复的问题
	if (newPwd1 == $("#newPwd1").attr("placeholder")) {
		newPwd1 = "";
	}

	if (newPwd1 == null || newPwd1 == "") {
		layer.tips('请输入密码', '#newPwd1', {
			tips : 3,
			time : 1000
		});
		return false;
	} else {
		if (!pwdReg.test(newPwd1)) {
			layer.tips('密码格式为6-15位非空字符!', '#newPwd1', {
				tips : 3,
				time : 2000
			});
			return false;
		} else {
			if (newPwd != newPwd1) {
				layer.tips('确认密码输入不一致，请检查输入的密码!', '#newPwd1', {
					tips : 3,
					time : 2000
				});
				return false;
			} else {
				return true;
			}
		}
	}
}

//修改密码
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
function savePassword() {
	var userId = $("#userId").val();
	var loginName = $("#loginName").val();
	var newPwd = $("#newPwd").val();
	
	
	if (checkCode() && checkNewPwd() && checkNewPwd1()) {
		newPwd = encrypt(newPwd, loginName);
		var index1 = layer.load(1);
		$.post(ctx + "/completePassword", {
			id : userId,
			loginName : loginName,
			newPwd : newPwd
		}, function(data) {
			data = JSON.parse(data);
			if (data.success) {
				layer.msg("操作成功", {
					icon : 1,
					time : 1000
				//2秒关闭（如果不配置，默认是3秒）
				}, function() {
					layer.close(index1);
					window.history.back(-1);
					parent.layer.close(index);
					
				});
			} else {
				layer.msg(data.msg, {
					icon : 2,
					time : 1000
				//2秒关闭（如果不配置，默认是3秒）
				}, function() {
					layer.close(index1);
				});
			}
		});
	}
}

function initListener() {
	$("#provinceId").change(
			function() {
				var provinceId = $("#provinceId").val();
				if (provinceId != "") {
					$.ajax({
						type : "GET",
						url : ctx + "/cellBuilding/getCellRegionByCellId",
						cache : "false",
						dataType : "json",
						data : {
							cellid : cellid
						},
						success : function(data) {
							if (data.success) {
								var result = "<option value='"
										+ "'>--市--</option>";
								$.each(data.obj, function(index, item) {
									result += "<option id='" + item.name + "'"
											+ " value='" + item.id + "'>"
											+ item.name + "</option>";
								});
								$("#regionid").html("");
								$("#regionid").append(result);
							}
						}
					})
				} else {
					var result = "<option value='" + "'>--区域--</option>";
					$("#regionid").html("");
					$("#regionid").append(result);
				}
			});
}


//检查必须项
function checkInput(id, tip){
    if($('#' + id +'').length <= 0 ) {
        return true;
    }
    var value = $('#' + id +'').val();
    //解决ie9以下placeholder与value重复的问题
    if(value == $('#' + id +'').attr("placeholder")){
        value = "";
    }
    if(value == null || value == ""){
        layer.tips(tip, '#' + id +'', {
            tips: 3,
            time:1000
        });
        return false;
    } else{
        return true;
    }
}